package com.msxt.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.msxt.annotation.IgnoreAuth;
import com.msxt.constant.JwtClaimsConstant;
import com.msxt.dto.YonghuEntity;
import com.msxt.properties.JwtProperties;
import com.msxt.result.R;
import com.msxt.service.YonghuService;
import com.msxt.utils.JwtUtil;
import com.msxt.utils.MPUtil;
import com.msxt.utils.PageUtils;
import com.msxt.view.YonghuView;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/yonghu")
public class YonghuController {
	@Autowired
	private YonghuService yonghuService;

	@Autowired
	private JwtProperties jwtProperties;

	// OSS基础URL配置
	@Value("${oss.base-url:}")
	private String ossBaseUrl;

	/**
	 * 登录（支持GET和POST）
	 */
	@IgnoreAuth
	@RequestMapping(value = "/login", method = {RequestMethod.GET, RequestMethod.POST})
	public R login(
			@RequestParam(value = "username", required = true) String username,
			@RequestParam(value = "password", required = true) String password,
			HttpServletRequest request) {

		log.info("用户登录请求 - 用户名: {}, 方法: {}", username, request.getMethod());

		YonghuEntity user = yonghuService.getOne(new QueryWrapper<YonghuEntity>().eq("yonghuzhanghao", username));
		if(user == null) {
			log.warn("用户不存在: {}", username);
			return R.error("账号或密码不正确");
		}

		if(!user.getMima().equals(password)) {
			log.warn("密码错误: 用户 {}", username);
			return R.error("账号或密码不正确");
		}

		Map<String, Object> claims = new HashMap<>();
		claims.put(JwtClaimsConstant.YOONGHU_ID, user.getId());
		claims.put(JwtClaimsConstant.USERNAME, username);
		claims.put(JwtClaimsConstant.ROLE, "用户");
		claims.put(JwtClaimsConstant.TABLE_NAME, "yonghu");

		String token = JwtUtil.createJWT(
				jwtProperties.getUserSecretKey(),
				jwtProperties.getUserTtl(),
				claims);

		log.info("用户登录成功: {}", username);
		return R.ok().put("token", token);
	}

	/**
	 * 注册
	 */
	@IgnoreAuth
	@PostMapping("/register")
	public R register(@RequestBody YonghuEntity yonghu) {
		if(yonghuService.getOne(new QueryWrapper<YonghuEntity>().eq("yonghuzhanghao", yonghu.getYonghuzhanghao())) != null) {
			return R.error("注册用户已存在");
		}

		// 使用更可靠的ID生成方式
		yonghu.setId(System.currentTimeMillis() + new Random().nextInt(1000));

		// 修复：添加头像URL处理
		if (StringUtils.isNotBlank(yonghu.getTouxiang())) {
			yonghu.setTouxiang(ensureFullUrl(yonghu.getTouxiang()));
		}

		yonghuService.save(yonghu);
		return R.ok();
	}

	/**
	 * 退出
	 */
	@GetMapping("/logout")
	public R logout(HttpServletRequest request) {
		request.getSession().invalidate();
		return R.ok("退出成功");
	}

	/**
	 * 获取当前用户信息
	 */
	@GetMapping("/session")
	public R getCurrUser(HttpServletRequest request) {
		// 从请求属性中获取用户ID
		Object userIdObj = request.getAttribute("userId");
		if (userIdObj == null) {
			log.warn("未找到用户ID属性");
			return R.error(401, "用户未登录");
		}

		Long id;
		try {
			id = Long.parseLong(userIdObj.toString());
		} catch (NumberFormatException e) {
			log.error("用户ID格式错误: {}", userIdObj);
			return R.error(401, "无效的用户ID");
		}

		log.info("获取用户ID: {}", id);

		YonghuEntity user = yonghuService.getById(id);
		if (user == null) {
			return R.error(401, "用户不存在");
		}

		// 确保头像URL是完整的
		user.setTouxiang(ensureFullUrl(user.getTouxiang()));

		return R.ok().put("data", user);
	}

	/**
	 * 密码重置
	 */
	@IgnoreAuth
	@PostMapping("/resetPass")
	public R resetPass(String username, HttpServletRequest request) {
		YonghuEntity user = yonghuService.getOne(new QueryWrapper<YonghuEntity>().eq("yonghuzhanghao", username));
		if(user == null) {
			return R.error("账号不存在");
		}
		user.setMima("123456");
		yonghuService.updateById(user);
		return R.ok("密码已重置为：123456");
	}

	/**
	 * 后端列表
	 */
	@GetMapping("/page")
	public R page(@RequestParam Map<String, Object> params,
				  YonghuEntity yonghu,
				  HttpServletRequest request) {
		QueryWrapper<YonghuEntity> wrapper = new QueryWrapper<>();
		PageUtils page = yonghuService.queryPage(params,
				MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(wrapper, yonghu), params), params));

		// 处理列表中的头像URL
		if (page != null && page.getList() != null) {
			for (Object item : page.getList()) {
				if (item instanceof YonghuEntity) {
					YonghuEntity entity = (YonghuEntity) item;
					entity.setTouxiang(ensureFullUrl(entity.getTouxiang()));
				}
			}
		}

		return R.ok().put("data", page);
	}

	/**
	 * 前端列表
	 */
	@IgnoreAuth
	@GetMapping("/list")
	public R list(@RequestParam Map<String, Object> params,
				  YonghuEntity yonghu,
				  HttpServletRequest request) {
		QueryWrapper<YonghuEntity> wrapper = new QueryWrapper<>();
		PageUtils page = yonghuService.queryPage(params,
				MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(wrapper, yonghu), params), params));

		// 处理列表中的头像URL
		if (page != null && page.getList() != null) {
			for (Object item : page.getList()) {
				if (item instanceof YonghuEntity) {
					YonghuEntity entity = (YonghuEntity) item;
					entity.setTouxiang(ensureFullUrl(entity.getTouxiang()));
				}
			}
		}

		return R.ok().put("data", page);
	}

	/**
	 * 列表
	 */
	@GetMapping("/lists")
	public R list(YonghuEntity yonghu) {
		QueryWrapper<YonghuEntity> wrapper = new QueryWrapper<>();
		wrapper.allEq(MPUtil.allEQMapPre(yonghu, "yonghu"));

		List<YonghuEntity> list = yonghuService.list(wrapper);

		// 处理列表中的头像URL
		for (YonghuEntity entity : list) {
			entity.setTouxiang(ensureFullUrl(entity.getTouxiang()));
		}

		return R.ok().put("data", list);
	}

	/**
	 * 查询
	 */
	@GetMapping("/query")
	public R query(YonghuEntity yonghu) {
		QueryWrapper<YonghuEntity> wrapper = new QueryWrapper<>();
		wrapper.allEq(MPUtil.allEQMapPre(yonghu, "yonghu"));
		YonghuView yonghuView = yonghuService.selectView(wrapper);

		// 处理头像URL
		if (yonghuView != null) {
			yonghuView.setTouxiang(ensureFullUrl(yonghuView.getTouxiang()));
		}

		return R.ok("查询用户成功").put("data", yonghuView);
	}

	/**
	 * 后端详情
	 */
	@GetMapping("/info/{id}")
	public R info(@PathVariable("id") Long id) {
		YonghuEntity yonghu = yonghuService.getById(id);

		// 确保头像URL是完整的
		if (yonghu != null) {
			yonghu.setTouxiang(ensureFullUrl(yonghu.getTouxiang()));
		}

		return R.ok().put("data", yonghu);
	}

	/**
	 * 前端详情
	 */
	@IgnoreAuth
	@GetMapping("/detail/{id}")
	public R detail(@PathVariable("id") Long id) {
		YonghuEntity yonghu = yonghuService.getById(id);

		// 确保头像URL是完整的
		if (yonghu != null) {
			yonghu.setTouxiang(ensureFullUrl(yonghu.getTouxiang()));
		}

		return R.ok().put("data", yonghu);
	}

	/**
	 * 后端保存
	 */
	@PostMapping("/save")
	public R save(@RequestBody YonghuEntity yonghu,
				  HttpServletRequest request) {
		// 使用更可靠的ID生成方式
		yonghu.setId(System.currentTimeMillis() + new Random().nextInt(1000));

		if(yonghuService.getOne(new QueryWrapper<YonghuEntity>().eq("yonghuzhanghao", yonghu.getYonghuzhanghao())) != null) {
			return R.error("用户已存在");
		}

		// 修复：添加头像URL处理
		if (StringUtils.isNotBlank(yonghu.getTouxiang())) {
			yonghu.setTouxiang(ensureFullUrl(yonghu.getTouxiang()));
		}

		yonghuService.save(yonghu);
		return R.ok();
	}

	/**
	 * 前端保存
	 */
	@PostMapping("/add")
	public R add(@RequestBody YonghuEntity yonghu,
				 HttpServletRequest request) {
		// 使用更可靠的ID生成方式
		yonghu.setId(System.currentTimeMillis() + new Random().nextInt(1000));

		if(yonghuService.getOne(new QueryWrapper<YonghuEntity>().eq("yonghuzhanghao", yonghu.getYonghuzhanghao())) != null) {
			return R.error("用户已存在");
		}

		// 修复：添加头像URL处理
		if (StringUtils.isNotBlank(yonghu.getTouxiang())) {
			yonghu.setTouxiang(ensureFullUrl(yonghu.getTouxiang()));
		}

		yonghuService.save(yonghu);
		return R.ok();
	}

	/**
	 * 修改用户信息（修复头像URL处理）
	 */
	@PostMapping("/update")
	@Transactional
	public R update(@RequestBody YonghuEntity yonghu,
					HttpServletRequest request) {
		// 先获取现有用户信息
		YonghuEntity existingUser = yonghuService.getById(yonghu.getId());
		if (existingUser == null) {
			return R.error("用户不存在");
		}

		// 只更新传入的非空字段
		if (yonghu.getYonghuzhanghao() != null) {
			// 检查用户名是否已存在（如果不是更新自己）
			if (!existingUser.getYonghuzhanghao().equals(yonghu.getYonghuzhanghao())) {
				YonghuEntity u = yonghuService.getOne(new QueryWrapper<YonghuEntity>()
						.eq("yonghuzhanghao", yonghu.getYonghuzhanghao()));
				if(u != null && !u.getId().equals(yonghu.getId())) {
					return R.error("用户名已存在");
				}
			}
			existingUser.setYonghuzhanghao(yonghu.getYonghuzhanghao());
		}

		if (yonghu.getMima() != null) {
			existingUser.setMima(yonghu.getMima());
		}

		if (yonghu.getYonghuxingming() != null) {
			existingUser.setYonghuxingming(yonghu.getYonghuxingming());
		}

		if (yonghu.getXingbie() != null) {
			existingUser.setXingbie(yonghu.getXingbie());
		}

		if (yonghu.getLianxifangshi() != null) {
			existingUser.setLianxifangshi(yonghu.getLianxifangshi());
		}

		if (yonghu.getTouxiang() != null) {
			// 处理空头像字段的情况
			if (yonghu.getTouxiang().isEmpty()) {
				// 保留原有头像（不更新）
				log.info("头像字段为空，保留原有头像");
			} else {
				// 修复：使用统一的URL处理方法
				existingUser.setTouxiang(ensureFullUrl(yonghu.getTouxiang()));
			}
		}

		if (yonghu.getAddtime() != null) {
			existingUser.setAddtime(yonghu.getAddtime());
		}

		yonghuService.updateById(existingUser);
		return R.ok();
	}

	/**
	 * 更新头像
	 */
	@PostMapping("/updateAvatar")
	public R updateAvatar(@RequestBody Map<String, Object> params) {
		try {
			Long id = Long.valueOf(params.get("id").toString());
			String avatarUrl = params.get("touxiang").toString();

			// 修复：使用统一的URL处理方法
			String processedAvatarUrl = ensureFullUrl(avatarUrl);

			YonghuEntity user = yonghuService.getById(id);
			if (user == null) {
				return R.error("用户不存在");
			}

			user.setTouxiang(processedAvatarUrl);
			yonghuService.updateById(user);

			return R.ok().put("data", processedAvatarUrl);
		} catch (Exception e) {
			log.error("更新头像失败: {}", e.getMessage());
			return R.error("更新头像失败");
		}
	}

	/**
	 * 删除
	 */
	@PostMapping("/delete")
	public R delete(@RequestBody Long[] ids) {
		yonghuService.removeByIds(Arrays.asList(ids));
		return R.ok();
	}

	/**
	 * 提醒接口
	 */
	@GetMapping("/remind/{columnName}/{type}")
	public R remindCount(@PathVariable("columnName") String columnName,
						 HttpServletRequest request,
						 @PathVariable("type") String type,
						 @RequestParam Map<String, Object> map) {
		map.put("column", columnName);
		map.put("type", type);

		if("2".equals(type)) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar c = Calendar.getInstance();
			Date remindStartDate = null;
			Date remindEndDate = null;
			if(map.get("remindstart") != null) {
				Integer remindStart = Integer.parseInt(map.get("remindstart").toString());
				c.setTime(new Date());
				c.add(Calendar.DAY_OF_MONTH, remindStart);
				remindStartDate = c.getTime();
				map.put("remindstart", sdf.format(remindStartDate));
			}
			if(map.get("remindend") != null) {
				Integer remindEnd = Integer.parseInt(map.get("remindend").toString());
				c.setTime(new Date());
				c.add(Calendar.DAY_OF_MONTH, remindEnd);
				remindEndDate = c.getTime();
				map.put("remindend", sdf.format(remindEndDate));
			}
		}

		QueryWrapper<YonghuEntity> wrapper = new QueryWrapper<>();
		if(map.get("remindstart") != null) {
			wrapper.ge(columnName, map.get("remindstart"));
		}
		if(map.get("remindend") != null) {
			wrapper.le(columnName, map.get("remindend"));
		}

		long count = yonghuService.count(wrapper);
		return R.ok().put("count", count);
	}

	/**
	 * 确保URL是完整的OSS URL
	 */
	private String ensureFullUrl(String url) {
		if (StringUtils.isBlank(url)) {
			return url;
		}

		// 如果已经是完整URL，直接返回
		if (url.startsWith("http://") || url.startsWith("https://")) {
			return url;
		}

		// 处理相对路径：移除可能重复的"upload/"前缀
		String cleanedUrl = url;
		if (cleanedUrl.startsWith("upload/")) {
			cleanedUrl = cleanedUrl.substring(7);
		}

		// 如果是相对路径，添加OSS基础URL
		if (StringUtils.isNotBlank(ossBaseUrl)) {
			// 确保OSS基础URL以斜杠结尾，而相对路径不以斜杠开头
			String baseUrl = ossBaseUrl.endsWith("/") ? ossBaseUrl : ossBaseUrl + "/";
			String relativePath = cleanedUrl.startsWith("/") ? cleanedUrl.substring(1) : cleanedUrl;
			return baseUrl + relativePath;
		}

		// 如果没有配置OSS基础URL，返回清理后的相对路径
		return cleanedUrl;
	}
}